package com.pig4cloud.pigx.common.websocket.custom;

import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 开放API ws握手拦截器
 *
 * @since 2022/11/13 18:45
 */
public class OpenApiHandshakeInterceptor implements HandshakeInterceptor {

	@Override
	public boolean beforeHandshake(ServerHttpRequest request,
								   ServerHttpResponse response,
								   WebSocketHandler wsHandler,
								   Map<String, Object> attributes) throws Exception {
		List<String> valueList = request.getHeaders().get(SecurityConstants.X_API_WS);
		// 存入null值会导致报错
		if (Objects.isNull(valueList)) {
			valueList = Collections.EMPTY_LIST;
		}

		// 保存是否为OpenApi请求的请求头参数
		attributes.put(SecurityConstants.X_API_WS, valueList);
		return true;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

	}
}
